-- KEYS[1] : 令牌剩余数
-- KEYS[2] : 上次补充时间戳
-- ARGV[1]: 桶容量
-- ARGV[2]: 补满周期(s)

local tokens_key   = KEYS[1]
local ts_key       = KEYS[2]
local capacity     = tonumber(ARGV[1])
local refill_time  = tonumber(ARGV[2])

local now   = redis.call("TIME")[1]           -- 秒级时间戳
local rate  = capacity / refill_time          -- 每秒生产速率

local last  = tonumber(redis.call("GET", ts_key)) or now
local tokens = tonumber(redis.call("GET", tokens_key)) or capacity

-- 补充令牌
tokens = math.min(capacity, tokens + (now - last) * rate)

local allowed = 0
if tokens >= 1then
    tokens = tokens - 1
    allowed = 1
end

-- 写回 Redis 并设置过期
redis.call("SETEX", tokens_key, refill_time, tokens)
redis.call("SETEX", ts_key, refill_time, now)

return allowed